package websocket

import (
	"gitee.com/injoyai/goutil/oss/io"
	"gitee.com/injoyai/goutil/oss/io/buf"
	"golang.org/x/net/websocket"
)

const origin = "http://localhost/"

// Client websocket的客户端
type Client struct {
	*io.Client
}

func (this *Client) NewMessageReader(f buf.ReadFunc) buf.MessageReader {
	this.SetReadWithNil()
	return buf.NewMessageReader(this.Client.Buffer(), f)
}

// Redial 重试连接
func (this *Client) Redial(fn ...func(c *Client)) *Client {
	var fns []func(c *io.Client)
	for _, v := range fn {
		fns = append(fns, func(c *io.Client) { v(&Client{c}) })
	}
	this.Client.Redial(fns...)
	return this
}

// Dial 建立websocket连接
func Dial(addr string) (*Client, error) {
	dial := func() (io.ReadWriteCloser, error) { return websocket.Dial(addr, "", origin) }
	ws, err := io.NewDial(dial)
	return &Client{ws.SetPrintWithASCII()}, err
}

// Redial 重试连接
func Redial(addr string, fn ...func(c *Client)) *Client {
	return MustDial(addr).Redial(fn...)
}

// MustDial 直到连接成功
func MustDial(addr string) *Client {
	return &Client{Client: io.MustClient(func() (io.ReadWriteCloser, error) {
		return websocket.Dial(addr, "", origin)
	})}
}
